package com.sgj.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: Guoji Shen
 * @Date: 2021/8/4 15:20
 */
public class LSaleTicket {

    public static void main(String[] args) {
        LTicket lTicket = new LTicket();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                lTicket.sale();
            }
        }, "AA").start();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                lTicket.sale();
            }
        }, "BB").start();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                lTicket.sale();
            }
        }, "CC").start();

    }
}

class LTicket {

    /**
     * 票数量
     */
    private int number = 30;

    // 创建可重入锁
    private final ReentrantLock lock = new ReentrantLock(true);

    /**
     * 卖票方法
     */
    public void sale() {
        // 上锁
        lock.lock();
        try {
            // 判断是否有票
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "  卖出：" + number-- + "张票  还剩：" + number + "张票！");
            } else {
                System.out.println("票卖完了！！");
            }
        } finally {
            // 解锁
            lock.unlock();
        }
    }
}